<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.io.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>

<%

/** 把那个小图片存起来 */
String type = request.getParameter("type");
if(null == type) type = "small";
//这里传过来会有两种类型，一先一后, big和small, 保存成功后返回一个json字串，客户端会再次post下一个.
String picId = request.getParameter("photoId");
//生成图片存放路径
String newAvatarPath = "/attachment/avatar/"+type+"/";


//错误信息
String errorMsg = "";
//文件最大值
long maxSize = 1000000;
//定义文件上传的类型
String[] types = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};


String fileExt = "jpg";
String tempName = picId+"_"+type+".jpg";

//保存报像头上传的图片.
String savePath = request.getSession().getServletContext().getRealPath("/")+newAvatarPath;

//上传后图片的url地址
String picRealPath = request.getContextPath() + newAvatarPath + tempName;

// picRealPath
//文件保存目录URL

//判断是否为单个文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if(isMultipart){
    
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List items = upload.parseRequest(request);
    // Process the uploaded items
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        //原文件名
        String fileName = item.getName();
        
        //文件大小
        long  fileSize  = item.getSize();
              
        if (!item.isFormField()) {
          //检查文件名
          if(item.getName()==""||item.getString()==null){
            errorMsg = "请选择文件。";
            break;
          }
          //检查目录
          File uploadDir = new File(savePath);
          if(!uploadDir.isDirectory()){
            errorMsg = "上传目录不存在。";
            break;
          }
          //检查目录写权限
          if(!uploadDir.canWrite()){
            errorMsg = "上传目录没有写权限。";
            break;
          }
          //检查文件大小
          if(item.getSize()>maxSize){
            errorMsg = "上传文件大小超过限制。";
          }
          //获得文件扩展名
          if(null == fileExt)
            fileExt = fileName.substring(fileName.indexOf(".")+1);
          if(!Arrays.<String>asList(types).contains(fileExt.toLowerCase())){
            errorMsg = "上传文件扩展名是不允许的扩展名。";
          } 
          
          //服务器上临时文件名
          // String tempName = new Date().getTime()+"."+fileExt;
          
          //检查是否已上传
          File file = new File(savePath+"\\"+tempName);
          if(file.exists()){
            errorMsg = "临时文件可能不是上传文件。";
          }
          //上传文件  
          try{
            File uploadedFile = new File(savePath,tempName);
              
            item.write(uploadedFile);
          }catch(Exception e){
            errorMsg = "上传文件失败。";
          }
          
        }
    }
    
    if(errorMsg.equals("")){
        //输出新保存的图片位置, 测试时注意改一下域名路径, 后面的statusText是成功提示信息.
        //status 为1 是成功上传，否则为失败.
        String jsondata = "{photoId: '"+picId+"',"+
        "urls: {'"+picRealPath+"'},"+
        "status: '1',"+
        "statusText = '上传成功!'"+
        "}";
        out.println(jsondata);
        //$d->data->urls[0] = 'http://sns.com/avatar_test/'.$new_avatar_path;
    }else{
        String jsondata = "{"+
        "status: '0',"+
        "statusText = '上传失败!'"+
        "}";
        out.println(jsondata);
    }
    
  }


%>